package com.example.demo.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@ControllerAdvice  // （1）随着 Spring 的启动而启动，（2）会监督 controller里边的异常
@ResponseBody
// 1、创建一个异常处理类
public class MyExceptionAdvice {

    /**
     * 处理空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)  // 检测空指针异常
    // 2、创建异常检测的类和处理业务方法
    public HashMap<String, Object> doNullPointerException(NullPointerException e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", -1);
        result.put("msg", "空指针：" + e.getMessage());
        result.put("data", null);
        return result;
    }

    /**
     * 默认的异常处理（当具体的异常匹配不到时，会执行此方法）
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public HashMap<String, Object> doException(Exception e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", -1);
        result.put("msg", "Exception：" + e.getMessage());
        result.put("data", null);
        return result;
    }
}
